const express = require("express");
const Result = require("../models/Result");
const { login, findUser } = require("../service/user"); // 从服务层 引入业务逻辑
const { md5, decode } = require("../utils/index");
const { PWD_SALT } = require("../utils/constant");
const { body, validationResult } = require("express-validator"); //参数校验
const boom = require("boom");
const jwt = require("jsonwebtoken"); //jwt
const { PRIVATE_KEY, JWT_EXPIRED } = require("../utils/constant"); //jwt 私钥+过期时间

const router = express.Router();

router.get("/info", function (req, res, next) {
  const decodeReq = decode(req); // 从head中解出数据
  if (decodeReq && decodeReq.username) {
    findUser(decodeReq.username)
      .then((user) => {
        console.log(user);
        if (user) {
          user.roles = [user.role]; // 返回结果，添加1个role数组
          new Result(user, "用户信息查询成功").success(res);
        } else {
          new Result("用户信息查询失败").fail(res);
        }
      })
      .catch((err) => {
        new Result("用户信息查询失败").fail(res);
      });
  }
});

router.post(
  "/login",
  [
    body("username").isString().withMessage("用户名必须为字符"), //body 是个函数
    body("password").isString().withMessage("密码必须为数字"),
  ],
  function (req, res, next) {
    const validerr = validationResult(req); //验证结果
    if (!validerr.isEmpty()) {
      const [{ msg }] = validerr.errors; // 通过解构，获取 报错信息
      next(boom.badRequest(msg)); //把异常传递下去
    }
    console.log("/user/login", req.body);
    let { username, password } = req.body;
    // 查询数据库
    password = md5(`${password}${PWD_SALT}`); // 加密
    login(username, password)
      .then((user) => {
        if (!user || user.length === 0) {
          //为空 或 长度为0
          new Result("登录失败").fail(res);
        } else {
          //JWT 生成私钥
          const token = jwt.sign(
            { username }, //data
            PRIVATE_KEY, //私钥
            {
              expiresIn: JWT_EXPIRED,
            }
          );
          new Result({ token }, "登录成功").success(res);
        }
      })
      .catch((err) => {
        // console.log(err);
      });
  }
);

module.exports = router;
